string,null is not assignable to type string TS 2322

Descripcion

Al utilizar la siguiente linea para consultar el valor de un Path variable:

this.name = this.route.snapshot.paramMap.get('name');

Obtenemos el siguiente error:

Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.ts(2322)

              


        
Solucion

Para solucionar este error tenemos varias maneras:

Haciendo un casting a tipo string:

this.name = String(this.route.snapshot.paramMap.get('name'));

Haciendo una comprobacion tipo OR con un objeto vacio, de esta manera en caso de que devuelva null se devolverá el objeto vacio:

this.name = this.route.snapshot.paramMap.get('name') || '{}';

Usando el operador "!" al final de la expresion:

this.name = this.route.snapshot.paramMap.get('name')!;

Cambiando el archivo de configuracion tsconfig.json, tendriamos que añadir la siguiente opcion:

"strictNullChecks": false
Tags

java | Angular | Path variable | string | null